﻿using EntityModels.Entities;
using EntityModels.Normal;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System.Text.Json;

namespace EntityModels.DbContexts
{
    /// <summary>
    /// 值转换器
    /// </summary>
    public class ValueConverterDbContext : DbContext
    {
        public DbSet<ValueConverterDbContext> ValueConverterDbContexts => Set<ValueConverterDbContext>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 定义值转换器对象
            var converter = new ValueConverter<DataPackage, string>(
                // 从 .NET对象到数据库列值的转换
                d => JsonSerializer.Serialize(d, (JsonSerializerOptions)null),
                // 从数据库列值到 .NET对象的转换
                d => JsonSerializer.Deserialize<DataPackage>(d, (JsonSerializerOptions)null));

            // 引用值转换器对象
            modelBuilder.Entity<ValueConvertionEntity>()
                .Property(v => v.DataPackage)
                // 配置值转换器
                .HasConversion(converter);

            // 临时定义值转换表达
            modelBuilder.Entity<ValueConvertionEntity>()
                .Property(v => v.DataPackage)
                .HasConversion(
                d => JsonSerializer.Serialize(d, (JsonSerializerOptions)null),
                d => JsonSerializer.Deserialize<DataPackage>(d, (JsonSerializerOptions)null));

            // 使用预定义值转换器
            modelBuilder.Entity<ValueConvertionEntity>()
            .Property(v => v.PrimitiveTypesData)
            // 根据属性类型类型参数自动选择值转换器（此处是BoolToStringConverter）
            .HasConversion<string>();

        }

    }
}
